package dq.study.shiro.encrypt;

import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;

import java.security.Key;

/**
 * 加密解密
 * 目前shiro只支持对称加密 eg.AES Blowfish
 * @author dongqun
 * @date 2020/4/13 14:31
 */
public class EncryptDecrypt {

    private static AesCipherService service;
    private static Key key;
    static {
        service = new AesCipherService();
        service.setKeySize(128);
        key = service.generateNewKey();
    }


    public static String encrypt(String source){
        return service.encrypt(source.getBytes(),key.getEncoded()).toHex();//byte->hex string
    }

    public static String decrypt(String ciphertext){
        //hex string -> byte
        return new String(service.decrypt(Hex.decode(ciphertext),key.getEncoded()).getBytes());
    }

    public static void main(String[] args){
        String cipher = encrypt("hello");
        System.out.println(cipher);
        String source = decrypt(cipher);
        System.out.println(source);
    }

}
